const fs = require("fs");
const my_fs = require("./fs");
const multer = require("multer");
const bodyParser = require("body-parser");
const moment = require("moment");
// const express = require("express");
// const router = null;
const http = require("http");
var _this;

class MyFn {
  constructor(router) {
    this.name = "后台工具类";
    this.router = router;
    this.uploadFolder = "./files/";
    this.uploads = {};
    this.tempPath = "";
    this.allArr = [];
  }

  init() {
    _this = this;
    this.handleDir(this.uploadFolder);
  }

  // 获取所有项目...
  async getAll(req, res, next) {
    // console.log(_this);
    let ret = await my_fs.getAllDirOnly(_this.uploadFolder);

    let arr = [];

    ret.forEach((ele) => {
      let json = my_fs.getInfo(_this.uploadFolder + ele + "/", ele);
      arr.push(json);
    });
    // console.log(arr);
    _this.allArr = arr;
    res.json({ arr });
  }

  // 校验是否存在某项目
  async checkPath(name) {
    let flag = false;
    let ret = await my_fs.getAllDirOnly(_this.uploadFolder);
    ret.forEach((ele) => {
      if (ele == name) flag = true;
    });
    console.log("flag:", flag);
    return flag;
  }

  // 选择项目
  changePrj(req, res, next) {
    console.log("change prj ...");
    let data = req.body.data;
    // console.log('-- data -- -- --');
    // console.log(data);
    // console.log('-- data -- -- --');
    let path = data.path;
    let dirName = data.dirName;
    // console.log(path);
    _this.tempPath = dirName;

    _this.tempPath = path;
    _this.handleDir(path, dirName);

    res.json({ msg: "收到项目path:" + path });
  }

  // 上传接口
  async apker(req, res, next) {
    let file = req.file;
    let fileInfo = {};
    // created time
    let createtime = moment().format("YYYY-MM-DD HH:mm:ss");
    let time = moment().format("YYYY-MM-DD");

    // 获取文件信息 destination
    fileInfo.mimetype = file.mimetype;
    fileInfo.originalname = file.originalname.replace(".apk", "");
    fileInfo.size = file.size;
    fileInfo.path = file.path;
    fileInfo.destination = file.destination;
    fileInfo.createtime = createtime;
    fileInfo.time = time;

    // 设置响应类型及编码
    res.set({
      "content-type": "application/json; charset=utf-8",
    });
    // file info
    console.log("file ------------------------------");
    console.log(fileInfo);
    let arr = my_fs.setInfo(file.destination, fileInfo);

    // log
    let up = await my_fs.read("./log/upload.json");
    up = JSON.parse(up);
    if (up == false || up.record == []) {
      up = {
        record: [],
      };
    }
    up.record.unshift({ ip: req.ip, time: createtime });
    let up_json = await my_fs.write("./log/upload.json", JSON.stringify(up));

    res.json(fileInfo);
  }

  // 文件夹准备
  handleDir(path, dirName) {
    console.log("handle-dir...");
    // 1、打开文件夹
    try {
      fs.accessSync(path); // 打开文件夹
    } catch (e) {
      fs.mkdirSync(path); // 创建文件夹
    }

    let storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, path); // 他会放在当前目录下的 /upload 文件夹下（没有该文件夹，就新建一个）
      },
      filename: function (req, file, cb) {
        // 在这里设定文件名
        cb(null, file.originalname); // file.originalname是将文件名设置为上传时的文件名，file中携带的
        // cb(null, file.originalname + "-" + Date.now()) // 加上Date.now()可以避免命名重复
      },
    });

    if (!_this.router) return;
    let upload = multer({ storage: storage });
    console.log("path: /" + dirName);

    _this.uploads[dirName] = upload;

    _this.router.post(
      "/" + dirName,
      _this.uploads[dirName].single("apk"),
      _this.apker
    );
  }

  // 获取新版本信息
  async get_version(req, res, next) {
    console.log("get_version body");
    console.log(req.body);
    if (
      JSON.stringify(req.body) == "{}" ||
      req.body == null ||
      req.body == undefined
    ) {
      console.log("未传参");
      res.json({ json: false, errorCode: "未传参" });
      return;
    }

    let check = await _this.checkPath(req.body.prjName);

    if (!check) {
      console.log("项目不存在");
      res.json({ flag: false, errorCode: 2, errorInfo: "项目不存在" });
      return;
    }
    // return
    // console.log("req");
    let flag = false;
    let body = req.body;
    let prjName = body.prjName;
    let old_v = body.version;
    let new_v = "";
    let url = null;

    // let files = (await _this.handleFiles(prjName)) || []; // 获取文件
    new_v = (await _this.versionInfo(prjName)) || []; // 获取文件

    console.log("new_v:" + new_v + ",old_v:" + old_v);

    if (new_v > old_v) {
      console.log("需要更新");

      flag = true;
      url = "/files/" + prjName + "/" + new_v + ".apk";
    } else {
      flag = false;
      console.log("已经是最新版本");
    }

    let json = {
      flag,
      newVersion: new_v,
      errorCode: 0,
      // url: "/files/apk/1.0.2.apk"
    };

    if (url) {
      json.url = url;
    }

    res.json(json);
  }

  // 处理文件
  async handleFiles(prjName) {
    let files = await my_fs.readDir("./files/" + prjName);
    let arr = [];
    // let ret = await my_fs.write("./files/vers.txt", "");
    for (let i = 0; i < files.length; i++) {
      let ele = files[i];
      let ext = ele.substring(ele.lastIndexOf(".") + 1);
      if (ext != "apk") continue;

      let e = ele.replace(".apk", "");
      arr.push(e);

      // let ret = await my_fs.write("./files/vers.txt", e + "\n");
    }
    console.log(arr);
    return arr;
  }

  // 处理文件
  async versionInfo(prjName) {
    let info = await my_fs.getInfo("./files/" + prjName + "/");
    let versions = info.versions;
    console.log("info...");
    console.log(info);
    if (versions.length > 0) {
      return versions[0].originalname;
    } else {
      return "0.0.0";
    }
  }

  // 初始化
  reset_info(req, res, next) {
    console.log("reset .....");
    console.log(req.headers);
    let body = req.body;
    console.log(body.data);

    let path = body.data.path;

    let json = {
      name: body.data.name,
      versions: [],
      edit: true,
    };

    // console.log(json);
    let ret = my_fs.emptyInfo(path, json);

    res.json({ ret });
  }

  // 新建项目
  async create_prj(req, res, next) {
    let data = req.body.data || false;
    let title = data.title;
    let path = data.path;

    // 1 判断文件夹是否存在
    let flag = true;
    let msg = "1";
    let all_dir = await my_fs.getAllDirOnly("./files/");
    all_dir.forEach((ele) => {
      if (ele == path) {
        console.log(path + "===" + ele);
        flag = false;
        msg = "项目路径已存在";
      }
    });
    // 2 新建文件夹
    if (flag) {
      try {
        fs.mkdirSync("./files/" + path);
      } catch (error) {
        console.log("错误:" + error);
        flag = false;
        msg = "后台创建项目文件夹失败，请联系管理员";
      }
    }
    // 3 在文件夹里编写json文件
    let obj = { name: title, versions: [], edit: true };
    let json = JSON.stringify(obj);
    let json_path = "./files/" + path + "/info.json";
    let ret = await my_fs.write(json_path, json);
    if (!ret) {
      flag = false;
      msg = "后台创建项目详情失败，请联系管理员!";
    }

    if (flag) {
      res.json({ data: 1 });
    } else {
      res.json({ data: -1, msg });
    }
  }

  // 检验密码
  check_lock(req, res, next) {
    let body = req.body;
    let psd = body.psd;
    if (psd === "yycloud509") {
      res.json({ lock: false });
    } else {
      res.json({ lock: true });
    }
  }
}
module.exports.MyFn = MyFn;